-- @see https://github.com/wangshub/hammerspoon-config/blob/master/weather/weather.lua
local apiUrl = "https://www.tianqiapi.com/api/?version=v1"

local weatherIcon = {
    loading = hs.image.imageFromPath('assets/weather/loading.ico'):setSize({ w = 20, h = 20 }),
    reload = hs.image.imageFromPath('assets/weather/reload.ico'):setSize({ w = 20, h = 20 }),
    lei = hs.image.imageFromPath('assets/weather/lei.ico'):setSize({ w = 20, h = 20 }),
    qing = hs.image.imageFromPath('assets/weather/qing.ico'):setSize({ w = 20, h = 20 }),
    wu = hs.image.imageFromPath('assets/weather/wu.ico'):setSize({ w = 20, h = 20 }),
    xue = hs.image.imageFromPath('assets/weather/xue.ico'):setSize({ w = 20, h = 20 }),
    yu = hs.image.imageFromPath('assets/weather/yu.ico'):setSize({ w = 20, h = 20 }),
    yujiaxue = hs.image.imageFromPath('assets/weather/yujiaxue.ico'):setSize({ w = 20, h = 20 }),
    yun = hs.image.imageFromPath('assets/weather/yun.ico'):setSize({ w = 20, h = 20 }),
    zhenyu = hs.image.imageFromPath('assets/weather/zhenyu.ico'):setSize({ w = 20, h = 20 }),
    yin = hs.image.imageFromPath('assets/weather/yin.ico'):setSize({ w = 20, h = 20 }),
    xiaoyu = hs.image.imageFromPath('assets/weather/xiaoyu.ico'):setSize({ w = 20, h = 20 }),
    bingbao = hs.image.imageFromPath('assets/weather/bingbao.ico'):setSize({ w = 20, h = 20 }),
    taifeng = hs.image.imageFromPath('assets/weather/taifeng.ico'):setSize({ w = 20, h = 20 }),
    shachen = hs.image.imageFromPath('assets/weather/shachen.png'):setSize({ w = 20, h = 20 }),
}

local weatherBar = hs.menubar.new()
weatherBar:setIcon(weatherIcon['loading'])
-- weatherBar:setTitle('查询天气中..')

local reloadItem = {
    title = '重新加载',
    image = weatherIcon['reload'],
    fn = function() fetchWeatherInfo(true) end
}

function fetchWeatherInfo(isReload)
    hs.http.asyncGet(apiUrl, nil, function(status, body, _)
        if status ~= 200 then
            hs.alert.show('fetchWeatherInfo error, status = ' .. status)
            return
        end

        local weatherMenu = {}
        json = hs.json.decode(body)
        for i, v in pairs(json.data) do
            if i == 1 then
                -- weatherBar:setTitle(v.wea)
                weatherBar:setIcon(weatherIcon[v.wea_img])
            end

            weatherMenu[i] = {
                image = weatherIcon[v.wea_img],
                title = string.format('%s%s %s %s', v.day, v.wea, v.tem, v.win_speed)
            }
        end
        table.insert(weatherMenu, reloadItem)
        weatherBar:setMenu(weatherMenu)

        if (isReload) then
            hs.alert.show(string.format('%s 天气预报已更新', json.city))
        end
    end)
end

fetchWeatherInfo(false)

